package uit.nfcmenu.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;


public class ImageLoader {
	String tag = ImageLoader.class.getSimpleName();

	int stub_id;
	FileCache fileCache;
	private boolean isThumbPlay;
	
	MemoryCache memoryCache = new MemoryCache();
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	
	ExecutorService executorService;

	public ImageLoader(Context context, boolean isPlay) {
		this.isThumbPlay = isPlay;
		fileCache = new FileCache(context);
		executorService = Executors.newFixedThreadPool(5);
	}


	public void displayImage(String url, ImageView imageView, int stub_id) {
		this.stub_id = stub_id;
		imageViews.put(imageView, url);
		Bitmap bitmap = memoryCache.get(url);
		if (bitmap != null)
			imageView.setImageBitmap(bitmap);
		else {
			// image not saved before, load to sdcard
			queuePhoto(url, imageView);
			imageView.setImageResource(stub_id);
		}
	}

	private void queuePhoto(String url, ImageView imageView) {
		PhotoToLoad p = new PhotoToLoad(url, imageView);
		executorService.submit(new PhotosLoader(p));
	}

	private Bitmap getBitmap48(String url) {

		Log.v(tag, url);
		Bitmap b = null;
		File f = fileCache.getFilePNG(url);

		// from SD cache
		b = decodeFile48(f);
		if (b != null) {
			Log.w(tag, "getBitmap48 sdcard null url="+url);
			return b;
		}

		Log.i(tag, "getBitmap48 ... download");
		URL imageUrl;
		try {
			imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			if (is == null) {
				return null;
			}
			b = BitmapFactory.decodeStream(is);
			// b = Bitmap.createScaledBitmap(b, 192, 192, true);

			// write bitmap to SDCard
			OutputStream os = new FileOutputStream(f);
			b.compress(Bitmap.CompressFormat.PNG, 100, os); // TODO last 70
			os.close();
		} catch (MalformedURLException e) {
			Log.e(tag, "cann't save"+e);
		} catch (FileNotFoundException e) {
			Log.e(tag, "cann't save"+e);
		} catch (IOException e) {
			Log.e(tag, "cann't save"+e);
		}

		return b;
	}

//	private Bitmap getBitmapFull(String url) {
//
//		Log.v(tag, "getBitmap48");
//		Bitmap b = null;
//		File f = fileCache.getFile(url);
//
//		// from SD cache
//		b = decodeFileFull(f);
//		if (b != null) {
//			Log.v(tag, "getBitmap48 ... null");
//			return b;
//		}
//
//		Log.v(tag, "getBitmap48 ... download");
//		URL imageUrl;
//		try {
//			imageUrl = new URL(url);
//			HttpURLConnection conn = (HttpURLConnection) imageUrl
//					.openConnection();
//			conn.setConnectTimeout(30000);
//			conn.setReadTimeout(30000);
//			conn.setInstanceFollowRedirects(true);
//			InputStream is = conn.getInputStream();
//			if (is == null) {
//				return null;
//			}
//			b = BitmapFactory.decodeStream(is);
//			// b = Bitmap.createScaledBitmap(b, 400, 400, true);
//
//			// / write bitmap to SDCard
//			OutputStream os = new FileOutputStream(f);
//			b.compress(Bitmap.CompressFormat.PNG, 70, os);
//			os.close();
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//		return b;
//	}
//
//	private Bitmap decodeFileFull(File f) {
//		// Bitmap src = BitmapFactory.decodeFile(f.getPath());
//		Bitmap src;
//		try {
//			src = BitmapFactory.decodeStream(new FileInputStream(f), null,
//					new BitmapFactory.Options());
//			return Bitmap.createBitmap(src);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//			return null;
//		}
//	}

	/**
	 * Create 48x48 bitmap
	 * 
	 * @param f
	 * @return
	 */
	private Bitmap decodeFile48(File f) {
		Bitmap src;
		try {
			src = BitmapFactory.decodeStream(new FileInputStream(f), null,
					new BitmapFactory.Options());
			Log.i(tag, "image in sdcard");
			return Bitmap.createBitmap(src);
		} catch (FileNotFoundException e) {
			//e.printStackTrace();
			Log.w(tag, "FileNotFoundException image not in sdcard");
			return null;
		}
	}

	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;

		PhotosLoader(PhotoToLoad photoToLoad) {
			this.photoToLoad = photoToLoad;
		}

		@Override
		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			Bitmap bmp;
//			if (isThumbPlay == false) {
				bmp = getBitmap48(photoToLoad.url);
//			} else {
//				bmp = getBitmapFull(photoToLoad.url);
//			}
			memoryCache.put(photoToLoad.url, bmp);
			if (imageViewReused(photoToLoad)) {
				return;
			}
			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
			Activity a = (Activity) photoToLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}

	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url)) {
			return true;
		}
		
		return false;
	}

	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null) {
				photoToLoad.imageView.setImageBitmap(bitmap);
			} else {
				photoToLoad.imageView.setImageResource(stub_id);
			}
		}
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}
}
